//
//  ScenicDetailViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/31.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ScenicDetailViewController.h"
#import "ScenicDetailModel.h"
#import "ScenicDatabaseManager.h"

@interface ScenicDetailViewController ()<UIScrollViewDelegate, MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *titleImage;
@property (nonatomic, strong) UIButton *collectButton;
@property (nonatomic, strong) ScenicDetailModel *model;
@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;
@property (nonatomic, strong) AppDelegate *app;

@end

@implementation ScenicDetailViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _app = [[AppDelegate alloc] init];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavigationBar];
    [self addIndicatorView];
    [self setUpData];
    [self addInternetObserver];
}

- (void)viewWillAppear:(BOOL)animated
{
   
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}



#pragma mark -- 解析数据
- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
    [self.indicatorView startAnimating];
    if (self.sid == 0) {
        self.sid = 26986;
    }
    NSString *urlString = [NSString stringWithFormat:@"http://webapi.yilule.com:5580//api/SingleRequest?count=6&sid=%ld", self.sid];
    
    NSString *url = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
        } else {
            NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *tempDict = [tempDic valueForKey:@"Ptd"];
            self.model = [[ScenicDetailModel alloc] init];
            [self.model setValuesForKeysWithDictionary:tempDict];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self addScrollView];
                [self collectOrNot];
                [self.indicatorView stopAnimating];
            });
        }
    }];
    [dataTask resume];
    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"🙅 您的当前网络中断或网络信号差, 请检查网络后重新进入!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
//        
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


#pragma mark -- 设置导航栏
- (void)setNavigationBar
{
   
    self.navigationItem.title = @"景点详情";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
   
    self.navigationItem.leftBarButtonItem = leftButton;
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] init];
    self.collectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.collectButton.frame = CGRectMake(0, 0, 32, 32);
    [self.collectButton setImage:[UIImage imageNamed:@"detailCollect.png"] forState:(UIControlStateNormal)];
    
    [self.collectButton setImage:[UIImage imageNamed:@"collectSelect.png"] forState:(UIControlStateSelected)];
    [self.collectButton addTarget:self action:@selector(actionRightButton:) forControlEvents:(UIControlEventTouchUpInside)];
    rightButton.customView = self.collectButton;
    rightButton.tintColor = [UIColor blueColor];
    self.navigationItem.rightBarButtonItem = rightButton;
}

// 判断是否已收藏
- (void)collectOrNot
{
     ScenicDetailModel *newModel = [[ScenicDatabaseManager shareManager] selectModelByName:self.model.Name];
    if ([newModel.Name isEqualToString:self.model.Name]) {
        self.collectButton.selected = YES;
    } else {
        self.collectButton.selected = NO;
    }
    
}



#pragma mark -- 布局视图
- (void)addScrollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
   
    self.scrollView.delegate = self;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.contentInset = UIEdgeInsetsMake(210, 0, 0, 0);
    self.titleImage = [[UIImageView alloc] init];
    self.titleImage.contentMode = UIViewContentModeScaleAspectFill;
    self.titleImage.layer.masksToBounds = YES;
    self.titleImage.frame = CGRectMake(0, -210.0f, kScreenWidth, 210);
    [self.titleImage sd_setImageWithURL:[NSURL URLWithString:self.model.SharePic] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    [self.scrollView addSubview:self.titleImage];
    
    // 标题的lable
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 30)];
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.font = [UIFont systemFontOfSize:23];
    titleLable.text = self.model.Name;
    [self.scrollView addSubview:titleLable];
    
    //介绍的lable
    UILabel *recommendLable = [[UILabel alloc] initWithFrame:CGRectMake(10, titleLable.bottom + 15, kScreenWidth - 15, 25)];
    recommendLable.text = self.model.Foreword;
    recommendLable.font = [UIFont systemFontOfSize:14];
    recommendLable.textAlignment = NSTextAlignmentCenter;
    CGRect newFrame = recommendLable.frame;
    newFrame.size.height = [ScenicDetailViewController cellHeightWithModel:self.model.Foreword font:14];
    recommendLable.frame = newFrame;
    [self.scrollView addSubview:recommendLable];
    
    // 图片
    UIImageView *detailImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 255) / 2, recommendLable.bottom + 20, 255, 50)];
    detailImageView.image = [UIImage imageNamed:@"DetailTitle.png"];
    
    // 图片上的label
    UILabel *imageLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 17, 255, 16)];
    imageLable.text = @"        具       体       详       情";
    imageLable.backgroundColor = [UIColor whiteColor];
    [detailImageView addSubview:imageLable];
    [self.scrollView addSubview:detailImageView];
    
    // 概括的lable
    UILabel *descripLable = [[UILabel alloc] initWithFrame:CGRectMake(10, detailImageView.bottom + 20, kScreenWidth - 15, 30)];
    descripLable.font = [UIFont systemFontOfSize:22];
    descripLable.text = @"概括:";
    
    [self.scrollView addSubview:descripLable];
    // 概括详细
    UILabel *descripeDetailLable = [[UILabel alloc] initWithFrame:CGRectMake(10, descripLable.bottom, kScreenWidth - 15, 50)];
    descripeDetailLable.font = [UIFont systemFontOfSize:14];
    NSString *newStr = [self.model.Introduction stringByReplacingOccurrencesOfString:@"一路乐" withString:@"驴友帮"];
    descripeDetailLable.text = newStr;
    descripeDetailLable.numberOfLines = 0;
    CGRect newFrame1 = descripeDetailLable.frame;
    newFrame1.size.height = [ScenicDetailViewController cellHeightWithModel:newStr font:14];
    descripeDetailLable.frame = newFrame1;
    [self.scrollView addSubview:descripeDetailLable];
    
    // 地址
    UILabel *addressLable = [[UILabel alloc] initWithFrame:CGRectMake(10, descripeDetailLable.bottom + 20, kScreenWidth - 15, 30)];
    addressLable.font = [UIFont systemFontOfSize:22];
    addressLable.text = @"地址:";
    [self.scrollView addSubview:addressLable];
    
    // 地址详细
    UILabel *addressDetailLable = [[UILabel alloc] initWithFrame:CGRectMake(10, addressLable.bottom, kScreenWidth - 15, 50)];
    addressDetailLable.font = [UIFont systemFontOfSize:14];
    addressDetailLable.text = self.model.Address;
    addressDetailLable.numberOfLines = 0;
    CGRect newFrame2 = addressDetailLable.frame;
    newFrame2.size.height = [ScenicDetailViewController cellHeightWithModel:self.model.Address font:14];
    addressDetailLable.frame = newFrame2;
    
    [self.scrollView addSubview:addressDetailLable];
    

    
    // 开放时间
    UILabel *openLable = [[UILabel alloc] initWithFrame:CGRectMake(10, addressDetailLable.bottom + 20, kScreenWidth - 15, 30)];
    openLable.font = [UIFont systemFontOfSize:22];
    openLable.text = @"开放时间:";
    [self.scrollView addSubview:openLable];
    // 开放时间详细
    UILabel *openDeatilLable = [[UILabel alloc] initWithFrame:CGRectMake(10, openLable.bottom, kScreenWidth - 15, 50)];
    openDeatilLable.font = [UIFont systemFontOfSize:14];
    openDeatilLable.numberOfLines = 0;
    openDeatilLable.text = self.model.OpenTime;
    CGRect newFrame4 = openDeatilLable.frame;
    newFrame4.size.height = [ScenicDetailViewController cellHeightWithModel:self.model.OpenTime font:14];
    openDeatilLable.frame = newFrame4;
    [self.scrollView addSubview:openDeatilLable];
    
    // 门票价格
    UILabel *feeLable = [[UILabel alloc] initWithFrame:CGRectMake(10, openDeatilLable.bottom + 20, kScreenWidth - 15, 30)];
    feeLable.font = [UIFont systemFontOfSize:22];
    feeLable.text = @"门票价格:";
    [self.scrollView addSubview:feeLable];
    // 门票价格详细
    UILabel *feeDeatilLable = [[UILabel alloc] initWithFrame:CGRectMake(10, feeLable.bottom, kScreenWidth - 15, 50)];
    feeDeatilLable.font = [UIFont systemFontOfSize:14];
    feeDeatilLable.numberOfLines = 0;
    feeDeatilLable.text = self.model.TicketsPrice;
    CGRect newFrame5 = feeDeatilLable.frame;
    newFrame5.size.height = [ScenicDetailViewController cellHeightWithModel:self.model.TicketsPrice font:14];;
    feeDeatilLable.frame = newFrame5;
    
    [self.scrollView addSubview:feeDeatilLable];
    
    self.scrollView.contentSize = CGSizeMake(kScreenWidth, feeDeatilLable.bottom + 80);
    
    [self.view addSubview:self.scrollView];
}


#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.view.center;
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 8; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}


//下拉放大顶部图片
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat f = scrollView.contentOffset.y;
    
    if (f < -210) {
        CGRect newF = self.titleImage.frame;
        newF.origin.y = f;
        newF.size.height = -f;
        self.titleImage.frame = newF;
    }
}

+ (CGFloat)cellHeightWithModel:(NSString *)str font:(NSInteger)font
{
    // 计算字符串高度
    // 字号一定与lable相等
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName];
    CGRect lableFrame = [str boundingRectWithSize:CGSizeMake(kScreenWidth - 15, 100000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
    return lableFrame.size.height;
}



- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionRightButton:(UIButton *)collectButton
{
   
    if (self.model) {
        ScenicDetailModel *newModel = [[ScenicDatabaseManager shareManager] selectModelByName:self.model.Name];
        if ([newModel.Name isEqualToString:self.model.Name]) {
            [[ScenicDatabaseManager shareManager] deleteByName:newModel.Name];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"取消收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
            // 创建按钮
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
             collectButton.selected = NO;
        } else {
        [[ScenicDatabaseManager shareManager] insertDatabaseWithModel:self.model];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
            // 创建按钮
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
            collectButton.selected = YES;
        }
        
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲,你的数据尚未加载完成,请稍后" preferredStyle:(UIAlertControllerStyleAlert)];
        // 创建按钮
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
   
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
